<template>
  <!--备用-->
  <a-layout id="components-layout-demo-top-side-2" style="height: 100%;">
    <a-layout-header class="sflheader">
      <!--<img src="https://digitalsecurity.oss-cn-hangzhou.aliyuncs.com/visit/static/img/logo.png" alt="" style="float: left;height: inherit;" >-->
      <!--<p style="display: inline-block;margin: 0 50px;font-size: 22px;">舍弗勒-安保管理系统</p>-->
      <p style="display: inline-block; font-size: 18px; color: #fff; float: left;">舍弗勒-安保管理系统</p>
      <img src="https://digitalsecurity.oss-cn-hangzhou.aliyuncs.com/visit/static/img/logo2.png" alt="" style="float: right;margin: 18px 10px 0px 10px" >

      <div style="float:right;margin-right: 10px;">
        <a-dropdown>
          <a class="ant-dropdown-link" @click="e => e.preventDefault()">
            <a-avatar style="backgroundColor:#00893d" icon="user" />
            <span style="color: #fff;font-size: 14px;">{{user.userNO}}</span>
          </a>
          <a-menu slot="overlay" style="top: 10px;">
            <!--<a-menu-item>-->
              <!--<a href="javascript:;" @click="changePassword">修改密码</a>-->
            <!--</a-menu-item>-->
            <a-menu-item>
              <a href="javascript:;" @click="quitLogin">退出登录</a>
            </a-menu-item>

          </a-menu>
        </a-dropdown>
      </div>

    </a-layout-header>
    <a-layout>
      <a-layout-sider width="200" style="background: #fff">
        <a-menu
          mode="inline"
          :default-selected-keys="['1']"
          :defaultOpenKeys="['1']"
          :style="{ height: '100%', borderRight: 0,overflowY: 'auto',
    overflowX: 'hidden',backgroundColor: '#e6e6e6' }"
          :open-keys.sync="openKeys"
          @openChange="onOpenChange"
          @click="menuClick"
          :defaultSelectedKeys="[$route.name]"
          :selectedKeys="[$route.name]"

        >
          <!-- 菜单遍历的开始 -->
          <template v-for="item in menuList">
            <!-- 如果当前遍历项没有children，视为子菜单项，注意所有的key都是path用于路由跳转，以及当前选中记录 -->
            <a-menu-item v-if="!item.children" :key="item.path">
              <router-link to="item.path" replace>{{ item.title }}</router-link>
            </a-menu-item>
            <!-- 否则视为子菜单，传入菜单信息并且运用下面定义的函数式组件 -->
            <sub-menu v-else :key="item.path" :menu-info="item" />
          </template>
          <!--:default-open-keys="openKeys"    添加这一句，只打开一个大类菜单，切换关闭其他菜单-->
          <!--          <a-sub-menu key="sub1">-->
          <!--            <span slot="title"><a-icon type="contacts" />访客管理</span>-->
          <!--            <a-menu-item key="visitorDetails">-->
          <!--              <router-link to="visitorDetails" replace>访客明细</router-link>]-->
          <!--            </a-menu-item>-->
          <!--            <a-menu-item key="visitorDataDisplay">-->
          <!--              <router-link to="visitorDataDisplay" replace>访客数据展示</router-link>-->
          <!--            </a-menu-item>-->
          <!--            <a-menu-item key="visitorDataQuery">-->
          <!--              <router-link to="visitorDataQuery" replace>访客数据查询</router-link>-->
          <!--            </a-menu-item>-->
          <!--            <a-menu-item key="visitorUnitCount">-->
          <!--              <router-link to="visitorUnitCount" replace>访客单位访问统计</router-link>-->
          <!--            </a-menu-item>-->
          <!--            <a-menu-item key="visitorPersonsCount">-->
          <!--              <router-link to="visitorPersonsCount" replace>访客单位人次统计</router-link>-->
          <!--            </a-menu-item>-->
          <!--            <a-menu-item key="intervDeptCount">-->
          <!--              <router-link to="intervDeptCount" replace>被访者部门人次统计</router-link>-->
          <!--            </a-menu-item>-->
          <!--          </a-sub-menu>-->

          <!--          <a-sub-menu key="sub2">-->
          <!--            <span slot="title"><a-icon type="car" />停车场管理</span>-->
          <!--            <a-menu-item key="carDetails">-->
          <!--              <router-link to="carDetails" replace>车辆明细</router-link>-->
          <!--            </a-menu-item>-->
          <!--            <a-menu-item key="carDataShow">-->
          <!--              <router-link to="carDataShow" replace>车位数据展示</router-link>-->
          <!--            </a-menu-item>-->
          <!--            <a-menu-item key="carDataQuery">-->
          <!--              <router-link to="carDataQuery" replace>车位数据查询</router-link>-->
          <!--            </a-menu-item>-->
          <!--            <a-menu-item key="carParkManage">-->
          <!--              <router-link to="carParkManage" replace>停车场远程管理</router-link>-->
          <!--            </a-menu-item>-->
          <!--          </a-sub-menu>-->

          <!--          <a-sub-menu key="sub3">-->
          <!--            <span slot="title"><a-icon type="cluster" />权限管理</span>-->
          <!--            <a-menu-item key="purviewGroupDef">-->
          <!--              <router-link to="purviewGroupDef" replace>权限组定义</router-link>-->
          <!--            </a-menu-item>-->
          <!--            <a-menu-item key="adminsDefinitionVisitor">-->
          <!--              <router-link to="adminsDefinitionVisitor" replace>管理员定义</router-link>-->
          <!--            </a-menu-item>-->
          <!--          </a-sub-menu>-->

          <!--          <a-sub-menu key="sub4">-->
          <!--            <span slot="title"><a-icon type="usergroup-add" />人事档案</span>-->
          <!--            <a-menu-item key="departDef">-->
          <!--              <router-link to="departDef" replace>部门定义</router-link>-->
          <!--            </a-menu-item>-->
          <!--            <a-menu-item key="personnelFile">-->
          <!--              <router-link to="personnelFile" replace>人员档案</router-link>-->
          <!--            </a-menu-item>-->
          <!--          </a-sub-menu>-->

          <!--          <a-sub-menu key="sub5">-->
          <!--            <span slot="title"><a-icon type="hdd" />设备管理</span>-->
          <!--            <a-menu-item key="placeDefinition">-->
          <!--              <router-link to="placeDefinition" replace>场所定义</router-link>-->
          <!--            </a-menu-item>-->
          <!--            <a-menu-item key="deviceDefinition">-->
          <!--              <router-link to="deviceDefinition" replace>设备定义</router-link>-->
          <!--            </a-menu-item>-->
          <!--          </a-sub-menu>-->

          <!--          <a-sub-menu key="sub6">-->
          <!--            <span slot="title"><a-icon type="setting" />系统设置</span>-->
          <!--            <a-menu-item key="systemDefinition">-->
          <!--              <router-link to="systemDefinition" replace>系统定义</router-link>-->
          <!--            </a-menu-item>-->
          <!--            <a-menu-item key="menuManage">-->
          <!--              <router-link to="menuManage" replace>菜单管理</router-link>-->
          <!--            </a-menu-item>-->
          <!--            <a-menu-item key="logQuery">-->
          <!--              <router-link to="logQuery" replace>日志查询</router-link>-->
          <!--            </a-menu-item>-->
          <!--          </a-sub-menu>-->

        </a-menu>
      </a-layout-sider>

      <!--右侧-->
      <a-layout style="padding: 10px">
        <!--面包屑导航-->
        <!-- <a-breadcrumb style="margin: 16px 0">
          <a-breadcrumb-item>Home</a-breadcrumb-item>
          <a-breadcrumb-item>List</a-breadcrumb-item>
          <a-breadcrumb-item>App</a-breadcrumb-item>
        </a-breadcrumb> -->
        <a-layout-content :style="{ background: '#fff', padding: '0px', margin: 0, minHeight: '280px' }">

          <router-view/>

        </a-layout-content>
      </a-layout>
    </a-layout>

    <!-- 模态框 -->
    <a-modal
      :destroyOnClose="true"
      :maskClosable="false"
      :keyboard="false"
      @ok="addAccountOk"
      @cancel="addAccountCancel"
      v-model="modalVisible"
      title="修改密码"
      width="400px"
      :bodyStyle="{padding: '20px 30px 20px 20px'}"
      :okText="'保存'"
      :confirmLoading="contentLoading"
    >
      <a-spin :spinning="contentLoading">
        <a-form :form="form" @submit="addAccountOk">

          <a-row :gutter="20">
            <a-col :span="24">
              <a-form-item label="原密码" :colon="false" :label-col="{span: 5}" :wrapper-col="{span: 19}" required>
                <a-input-password
                  placeholder="请输入原密码"
                  type="password"
                  v-decorator="['oldPassword', { rules: [{ required: true, message: '请输入原密码!' }] }]"
                >
                </a-input-password>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="新密码" :colon="false" :label-col="{span: 5}" :wrapper-col="{span: 19}" required>
                <a-input-password
                  placeholder="请输入新密码"
                  type="password"
                  v-decorator="['newPassword',
                { rules: [{ validator: checkPassword},
                ] }]"
                >
                </a-input-password>
              </a-form-item>
            </a-col>
            <!--<a-col :span="24">-->
            <!--<a-form-item label="确认密码" :colon="false" :label-col="{span: 5}" :wrapper-col="{span: 19}" required>-->
            <!--<a-input-password-->
            <!--placeholder="请输入确认密码"-->
            <!--type="password"-->
            <!--v-decorator="[-->
            <!--'qrPassword',-->
            <!--{-->
            <!--rules: [-->
            <!--{required: true, message: '请输入确认密码' },-->
            <!--{ validator: compareToFirstPassword,}-->
            <!--]-->
            <!--}-->
            <!--]"-->

            <!--&gt;-->
            <!--</a-input-password>-->
            <!--</a-form-item>-->
            <!--</a-col>-->
          </a-row>


        </a-form>
      </a-spin>
    </a-modal>

  </a-layout>
</template>

<script>
import { tableBoxHeight } from "@/api/communal";
import loginApi from "@/api/login";
import localezh_CN from 'antd/lib/locale-provider/zh_CN';
import { Menu } from 'ant-design-vue';//引用
import 'moment/locale/zh-cn';

// 定义函数式组件
const SubMenu = {
  template: `
      <a-sub-menu :key="menuInfo.path" v-bind="$props" v-on="$listeners">
        <span slot="title">
            <a-icon :type="menuInfo.icon" />{{ menuInfo.title }}
        </span>
        <template v-for="item in menuInfo.children">
          <a-menu-item v-if="!item.children" :key="item.path">
            <router-link :to="item.path" replace>{{ item.title }}</router-link>
          </a-menu-item>
          <sub-menu v-else :key="item.path" :menu-info="item" />
        </template>
      </a-sub-menu>
    `,
  name: 'SubMenu',
  // must add isSubMenu: true 此项必须被定义
  isSubMenu: true,
  props: {
    // 解构a-sub-menu的属性，也就是文章开头提到的为什么使用函数式组件
    ...Menu.SubMenu.props,
    // 接收父级传递过来的菜单信息
    menuInfo: {
      type: Object,
      default: () => ({}),
    },
  },
};

export default {
  components: {
    SubMenu
  },
  name:'',
  data() {
    return {
      // 菜单缩进
      inlineIndent:12,
      // 默认不折叠
      collapsed: false,
      // 选中的子菜单项
      defaultSelectedKeys: [this.$route.name],
      menuList: [],
      localezh_CN,
      rootSubmenuKeys: ['1', '2', '3', '4', '5', '6', '7'],
      openKeys: ['1'],
      user:{
        userNO:"--"
      },
      form: this.$form.createForm(this, {name: 'passwordFrom'}),
      contentLoading: false,
      modalVisible: false,

    }
  },
  beforeMount(){
    let _this = this;
    // console.log(this.$store.state.user);
    if (this.$store.state.user.userNO) {
      this.user = this.$store.state.user;
      this.menuList = this.$store.state.menuList;
      // console.log(this.menuList);
    } else {
      // this.$warning({
      //   title: '登录信息已失效，请重新登录！',
      //   okText:"去登录",
      //   maskClosable: false,
      //   keyboard: false,
      //   onOk() {
      //     return new Promise((resolve, reject) => {
      //       _this.$router.replace("/");
      //       this.$nextTick(()=>{
      //         this.$destroyAll();
      //       })
      //     }).catch(() => {});
      //   },
      //   onCancel() {},
      // });
    }

    // 刷新页面时左侧菜单不能展开之前选中的menu
    let lastname = localStorage.getItem("openKeys");
    // console.log(lastname);
    // console.log(lastname.split(","));
    if (lastname != null && lastname != undefined ){
      this.openKeys = lastname.split(",");
    }

  },
  mounted() {
    // console.log(localStorage.getItem("selectedKeys"));
    // console.log(this.$store.state.menuList);
    // console.log(this.$store.state.selectedKeys);
    this.getUserInform();
  },
  destroyed(){
    // 在页面销毁后
  },
  methods: {
    // 获取员工信息
    async getUserInform(){
      let res = await loginApi.getUserInfor();
      console.log(res.data);
      if (res.data.success) {
        if(res.data.result == null){

        } else {

        }
      } else {

      }
    },
    onOpenChange (openKeys) {
      // 将当前打开的父级菜单存入缓存中
      window.localStorage.setItem('openKeys', JSON.stringify(openKeys))
      //  控制只打开一个
      const latestOpenKey = openKeys.find(key => this.openKeys.indexOf(key) === -1);
      if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
        this.openKeys = openKeys;
      } else {
        this.openKeys = latestOpenKey ? [latestOpenKey] : [];
      }
    },

    // 点击菜单，路由跳转,注意的是当点击MenuItem才会触发此函数
    menuClick({ item, key, keyPath }) {
      // 获取到当前的key,并且跳转
      this.$router.push({
        path: key
      })
    },
    quitLogin(){
      // 退出清空登陆人信息
      localStorage.setItem("user", JSON.stringify({}));
      localStorage.setItem("state", JSON.stringify({
        selectedKeys: [""],
        user: {},
        menuList:[],
        isSuper:"否"
      }));
      localStorage.setItem("menuList", JSON.stringify([]));
      this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(localStorage.getItem("store"))))

      this.$router.replace('/')
    },
    changePassword() {
      this.modalVisible = true
    },
    //添加/修改账户
    addAccountOk(e) {
      this.form.validateFields( async (err, values) => {
        if (err) {
          // console.log(values);
          return
        }
        let param = this.form.getFieldsValue();
        param.userNo = this.$store.state.user.userName
        // console.log(param);
        this.contentLoading = true;
        let res = await loginApi.updateDtUserPassword(param);
        this.contentLoading = false;
        if (res.data.success) {
          this.$message.success(res.data.message);
          this.addAccountCancel();
        } else {
          this.contentLoading = false;
          this.$message.error(res.data.message);
        }
      })
    },
    //取消、关闭弹窗
    addAccountCancel() {
      this.contentLoading = false;
      this.modalVisible = false;
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.form;
      if (value && this.confirmDirty) {
        form.validateFields(['qrPassword'], {force: true});
      }
      callback();
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.form;
      if (value && value !== form.getFieldValue('password')) {
        callback('两次密码不一致!');
      } else {
        callback();
      }
    },
    checkPassword(rule, value, callback) {
      // 请输入8到16位的包含数字、字母、特殊字符组合的密码
      const pwdRegex = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,.\/]).{8,16}$/;
      // 请输入8到16位的包含数字、字母
      // reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/;
      const pwdRegex2 = new RegExp('^[^ ]*$');

      if (value.trim() == "") {
        callback(new Error('请输入新密码'))
      } else if (!pwdRegex2.test(value)) {
        callback(new Error('输入的密码包含空格'))
      } else if (/[\u4E00-\u9FA5]/g.test(value)) {
        callback(new Error('输入的密码包含中文'))
      } else if (!pwdRegex.test(value)) {
        callback(new Error('请输入8到16位的包含数字、字母、特殊字符组合的密码'))
      }
      callback()

    },

  },

}
</script>

<style scoped>
/*.sflheader{*/
  /*padding: 0 30px;*/
  /*text-align: left;*/
  /*background: #00893d url(https://digitalsecurity.oss-cn-hangzhou.aliyuncs.com/visit/static/img/sflheader.jpg) no-repeat center center;*/
/*}*/

</style>
